import { ChangeDetectionStrategy, Component, Injector, OnInit } from '@angular/core';
import { STColumn } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { UrlOfSystemTable } from '@routes/system/_base';
import { UserVO } from '@types';
import { NzFormatEmitEvent, NzTreeNode } from 'ng-zorro-antd/tree';

import { SystemDictService } from '../../dict/dict.service';
import { SystemEditUserComponent } from '../edit-user/edit-user.component';
import { SystemUserService } from '../user.service';

@Component({
    selector: 'app-system-user-list',
    templateUrl: './user-list.component.html',
    styleUrls: ['./user-list.component.less'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserListComponent extends UrlOfSystemTable implements OnInit {
    url: string = this.apiUrl.user.list;

    columns: STColumn[] = [
        {
            title: '编号',
            fixed: 'left',
            width: '50px',
            type: 'checkbox',
            className: 'text-center',
            exported: false
        },
        {
            title: '用户编号',
            index: 'userId',
            className: 'text-center',
            width: '130px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.userId }) }
        },
        {
            title: '用户名称',
            index: 'userName',
            className: 'text-center',
            width: '130px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.userName }) }
        },
        {
            title: '用户昵称',
            index: 'nickName',
            className: 'text-center',
            width: '130px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.nickName }) }
        },
        {
            title: '部门',
            index: 'dept.deptName',
            className: 'text-center',
            width: '130px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.dept?.deptName }) }
        },
        {
            title: '手机号码',
            index: 'phonenumber',
            className: 'text-center',
            width: '130px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.phonenumber }) }
        },
        {
            title: '状态',
            index: 'status',
            className: 'text-center',
            width: '130px',
            render: 'statusCustom'
        },
        {
            title: '创建时间',
            index: 'createTime',
            className: 'text-center',
            width: '200px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.createTime }) }
        },
        {
            title: '操作',
            className: 'text-center',
            buttons: [
                {
                    // text: '修改',
                    iif: item => item.userId !== 1,
                    tooltip: `修改`,
                    acl: ['admin', 'system:user:edit'],
                    icon: 'edit',
                    click: item => this.editUser(item)
                },
                {
                    // text: '删除',
                    iif: item => item.userId !== 1,
                    tooltip: '删除',
                    acl: ['admin', 'system:user:remove'],
                    icon: 'delete',
                    className: 'text-error',
                    click: item => this.delUser(item)
                },
                {
                    // text: '重置密码',
                    iif: item => item.userId !== 1,
                    tooltip: '重置密码',
                    acl: ['admin', 'system:user:resetPwd'],
                    icon: 'lock',
                    className: 'text-error',
                    click: item => this.resetPassWord(item)
                },
                {
                    // text: '角色',
                    iif: item => item.userId !== 1,
                    acl: ['admin', 'system:user:edit'],
                    tooltip: '角色',
                    icon: 'down-circle'
                }
            ]
        }
    ];

    searchSchema: SFSchema = {
        properties: {
            userName: {
                title: '用户名称',
                type: 'string',
                ui: {
                    placeholder: '请输入用户名称'
                }
            },
            phonenumber: {
                title: '手机号码',
                type: 'string',
                ui: {
                    placeholder: '请输入手机号码'
                }
            },
            status: {
                title: '状态',
                type: 'string',
                ui: {
                    placeholder: '请选择状态',
                    widget: 'select',
                    asyncData: () => this.injector.get(SystemDictService).getDicts('sys_normal_disable')
                }
            },
            range: {
                type: 'string',
                title: '创建时间',
                ui: {
                    widget: 'date',
                    mode: 'range',
                    placeholder: '选择时间段'
                }
            }
        }
    };

    /**
     * 节点数据
     */
    nodes: NzTreeNode[] = [];

    /**
     * 展开全部
     */
    nzExpandAll = false;

    checkedKeys: string[] = [];

    deptName: string = '';

    constructor(
        protected override injector: Injector,
        private sysUSrv: SystemUserService
    ) {
        super(injector);
    }

    override ngOnInit() {
        this.deptTreeSelect();
    }

    deptTreeSelect() {
        this.sysUSrv.deptTreeSelect().subscribe(res => {
            this.nodes = res.data!;
            this.nzExpandAll = false;
            this.cdRef.detectChanges();
            this.nzExpandAll = true;
            this.cdRef.detectChanges();
        });
    }

    /**
     * 获取提示信息
     * @param row
     */
    getPopConfirmText(row: any) {
        let text = row.status === '0' ? '停用' : '启用';
        return `确认要"${text}""${row.userName}"用户吗?`;
    }

    override reSetDataGet(event: any) {
        this.params = {};
        this.checkedKeys = [];
        this.st.reset(this.params);
    }

    /**
     * 更改状态确认
     * @param item
     * @param index
     */
    confirmStatus(item: any, index: number) {
        const text = item.status === '0' ? '停用' : '启用';
        const _status = item.status === '0' ? '1' : '0';
        this.sysUSrv.changeStatus({ userId: item.userId, status: _status }).subscribe(res => {
            this.msg.success(`${text}成功`);
            this.st.setRow(index, { status: _status }, { refreshSchema: true });
        });
    }

    /**
     * 更改状态取消
     * @param item
     * @param index
     */
    cancelStatus(item: any, index: number) {
        this.st.setRow(index, { status: item.status }, { refreshSchema: true });
    }

    nzEvent(event: NzFormatEmitEvent): void {
        const departmentId = event.node!.origin['id'] ?? '';
        if (departmentId) {
            this.params['deptId'] = departmentId;
            this.searchDataGet(this.params);
        }
    }

    addUser(): void {
        this.modal
            .creatStaticModal(SystemEditUserComponent, { item: {} }, 'lg', {
                nzTitle: '添加用户'
            })
            .subscribe(res => {
                if (res) {
                    this.st.reset();
                }
            });
    }

    // 弹出编辑框
    editUser(item: UserVO): void {
        this.modal
            .creatStaticModal(SystemEditUserComponent, { item, type: 'edit' }, 'lg', {
                nzTitle: `修改成员【${item.userName}】`
            })
            .subscribe(res => {
                if (res) {
                    this.st.reset();
                }
            });
    }

    // 重置密码
    resetPassWord(item: UserVO): void {
        this.modal
            .creatStaticModal(SystemEditUserComponent, { item, type: 'reset' }, 'md', {
                nzTitle: `重置 ${item.userName} 密码`
            })
            .subscribe(res => {
                if (res) {
                }
            });
    }

    /**
     *
     * @param item
     */
    delUser(item: UserVO) {
        this.modalSrv.confirm({
            nzTitle: '删除提示',
            nzContent: `确认删除用户为 ${item.userName} 的数据项？`,
            nzOnOk: () =>
                this.sysUSrv.delUsers(item.userId.toString()).subscribe(res => {
                    if (res.isComplete) {
                        this.msg.success('删除成功');
                    }
                    this.st.reload();
                })
        });
    }

    /**
     *
     * @param items
     */
    delUserS(items: UserVO[]) {
        this.modalSrv.confirm({
            nzTitle: '删除提示',
            nzContent: `确认删除用户为 ${items.map(xx => xx.userName).join(',')} 的数据项？`,
            nzOnOk: () =>
                this.sysUSrv.delUsers(items.map(xx => xx.userId).join(',')).subscribe(res => {
                    if (res.isComplete) {
                        this.msg.success('删除成功');
                    }
                    this.st.reload();
                })
        });
    }
}
